// pages/useredit/edit.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userId: '',
    username: '',
    phone: '',
    email: '',
    password: '',
    //API
    getUserURL: app.globalData.api.applets.getuser(),
    updateUserURL: app.globalData.api.applets.updateuser(),
    addUserURL: app.globalData.api.applets.adduser()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var userId = options.userId;
    // this.setData({
    //   userId: options.userId
    // });

    if (undefined == userId) {
      return;
    }
    wx.request({
      url: app.globalData.api.applets.getuser(),
      data: {
        'userId': userId
      },
      success: function (res) {
        
        if (res.data.result) {

          that.setData({
            userId: res.data.resultData.id,
            username: res.data.resultData.username,
            phone: res.data.resultData.phone,
            password: res.data.resultData.password,
            email: res.data.resultData.email
          });
          //console.log(that.data);
          //console.log('---------' + that.data.userId);

        } else {
          wx.showToast({
            title: res.data.message,
            icon: '',
            duration: 2000,
          });
        }
      }
    });
    //console.log(that.data);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 表单提交函数
    */
  submitUser: function (e) {
    var that = this;
    var formData = e.detail.value;
    var url = that.data.addUserURL;
    if ('' != that.data.userId) {
      url = that.data.updateUserURL
      formData.userId = that.data.userId;
    }
    wx.request({
      url: url,
      // data: JSON.stringify(formData),
      //data: formData,
      data: {
        'password': formData.passwod,
        'phone': formData.phone,
        'username': formData.username,
        'email': formData.email,
        "userId":formData.userId
      },
      method: 'POST',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      },
      success: function (e) {
        wx.showToast({
          title: e.data.message,
          icon: '',
          duration: 2000,
        });
        if (e.data.result) {
          wx.navigateTo({
            url: '../list/list',
          })
        }
      }
    });

  }
})